<template>
  <div ref="chartRef" style="width:100%;height:600px"></div>
</template>
<script lang="ts">
  import {defineComponent, onMounted, ref, Ref, unref, watch, watchEffect} from 'vue';
  import {useECharts} from "@/hooks/web/useECharts";


  export default defineComponent({
    props: {
      dataSource: {
        type: Object,
        default: [],
      },
      chartName: {
        type: String,
        default: ""
      }
    },
    setup(props) {

      const chartData = ref([]);
      const chartRef = ref<HTMLDivElement | null>(null);
      const {setOptions} = useECharts(chartRef as Ref<HTMLDivElement>);

      watch(() => unref(props).dataSource, () => {
          chartData.value = unref(props).dataSource;
          loadChartDataSetOptions()
        }
      );
      watch(unref(chartData), () => {
        loadChartDataSetOptions()
      });

      function loadChartDataSetOptions() {

        setOptions({
          title: {
            left: 'center',
            text: unref(props).chartName,
          },
          tooltip: {
            trigger: 'axis',
            axisPointer: {
              lineStyle: {
                width: 1,
                color: '#019680',
              },
            },
          },
          xAxis: {
            type: 'value',
          },
          yAxis: generateYAxis(),
          grid: {left: '1%', right: '3%', top: '10%', bottom: '5%', containLabel: true},
          series: generateSeries(),
        });
      }


      function generateYAxis(): any {


        function getCatalogData(): any[] {
          let dataArray = [];
          if (unref(chartData)) {
            unref(chartData).forEach(data => {
              dataArray.push(data.userId || data.chanName)
            });
          }
          return dataArray
        }

        return {
          type: 'category',
          data: getCatalogData(),
          inverse: true,
          name: unref(props).chartName == "玩家充值排行" ? "用户ID" : "渠道昵称",
          nameLocation:"start"
        }
      }


      function generateSeries(): any[] {
        let series = [];

        function getDataListByProperName(properName) {
          let data = [];
          if (unref(chartData)) {
            unref(chartData).forEach(value => {
              data.push(value[properName])
            });
          }
          return {
            type: 'bar',
            stack: 'Total',
            data: data,
            barWidth: "30px",
            label: {
              position: 'right',
              show: true
            },
          }
        }

        series.push(getDataListByProperName("rechargeMoney"));
        return series
      }


      onMounted(() => {
        chartData.value = unref(props).dataSource;
        loadChartDataSetOptions()
      });

      return {chartRef};
    },
  });
</script>
